<template>
  <view class="container">
    <view class="form">
      <view class="form-item">
        <text class="label">姓名</text>
        <input type="text" style="width: 80vw;" placeholder="请输入姓名" v-model="name" readonly  />
      </view>
      <view class="form-item">
        <text class="label">电话号码</text>
        <input type="text" style="width: 80vw;" placeholder="请输入电话号码" v-model="phone" readonly />
      </view>
      <view class="form-item">
        <text class="label" @tap="getLocation">点击获取当前位置</text>
		<input type="text" style="width: 80vw;" placeholder="省" v-model="province" />
        <input type="text" style="width: 80vw;" placeholder="市" v-model="city" />
		<input type="text" style="width: 80vw;" placeholder="区" v-model="district" />
      </view>
      <view class="form-item">
        <text class="label">详细地址</text>
        <input type="text" style="width: 80vw;" placeholder="请输入详细地址" v-model="street" />
      </view>
    </view>
    <button class="submit-button" @click="submitAddress">提交</button>
  </view>
</template>

<script setup>
import { ref , onMounted} from 'vue';
import { onLoad } from '@dcloudio/uni-app';

onLoad((id) => {
  addressid.value = id.addressid;
  console.log('addressid:', addressid.value);
});
// 定义响应式数据
const address = ref('');
const name = ref('');
const phone = ref('');

const longitude=ref('');//经度
const latitude=ref('');//纬度
const province = ref(''); // 省
const city = ref(''); // 市
const district = ref(''); // 区
const street = ref(''); // 街道
const postalcode=ref('');//邮政编码

const addressid=ref('');//地址id

  const app = getApp();
  const url = app.globalData.url;
onMounted(() => {
	uni.request({
		url:url+"USER-SERVICE/customerCategory/addressesid",
		method:'POST',
		data:addressid.value,
		success(response) {
			 if (response.statusCode === 200) {
			        const data = response.data; // 获取返回的地址数据
			        console.log("通过id返回的地址数据:", data);
			
			        // 将数据赋值给响应式变量
			        name.value = data.customer.customerName; // 姓名
			        phone.value = data.customer.customerPhone; // 电话
			        longitude.value = data.longitude; // 经度
			        latitude.value = data.latitude; // 纬度
			        province.value = data.state; // 省
			        city.value = data.city; // 市
			        district.value = data.addressline2; // 区（根据数据，addressline2 是区）
			        street.value = data.addressline1; // 街道（根据数据，addressline1 是街道）
			        postalcode.value = data.postalcode; // 邮政编码
			      } else {
			        console.error("请求成功，但返回的状态码不是 200:", response.statusCode);
			      }
		}
	})
})
// 提交地址信息
const submitAddress = () => {
  if (!name.value || !phone.value  || !province.value || !city.value || !district.value) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    });
    return;
  }
  // 确定后跳转到另一个页面，并携带 addressid
  const apiKey = 'fb7014bb45af62eac3d0a2e34eb63918'; // 替换为你的高德API Key
  const fullAddress = `${province.value} ${city.value} ${district.value} ${street.value}`.trim();
  if (!fullAddress) {
  	uni.showToast({
  		title: '请输入完整的地址',
  		icon: 'none'
  	});
  	return;
  }
  // 调用高德地图的地理编码接口
  uni.request({
  	url: `https://restapi.amap.com/v3/geocode/geo?key=${apiKey}&address=${encodeURIComponent(fullAddress)}`,
  	method: 'GET',
  	success: (res) => {
  		if (res.data.status === '1' && res.data.geocodes && res.data.geocodes.length > 0) {
  			const location = res.data.geocodes[0].location.split(',');
				longitude.value=location[0];//经度
				latitude.value=location[1];//纬度
  				const app = getApp();
  				const url = app.globalData.url;
  				const addresses = {
  					addressid: addressid.value, // 假设用户ID为1，实际应从登录状态获取
  				    addressline1: street.value,
  				    addressline2: district.value,
  				    city: city.value,
  				    state: province.value,
  				    postalcode: postalcode.value, // 邮政编码，可选
  				    latitude: parseFloat(latitude.value),
  				    longitude: parseFloat(longitude.value)
  				  };
  					  uni.request({
  					    url: url+'USER-SERVICE/customerCategory/updateaddresses', 
  					    method: 'POST',
  					    data: addresses,
  					    success(response) {
  					      if (response.data === 1) {
  					        uni.showToast({
  					          title: "地址修改成功",
  					          icon: "success"
  					        });
  							uni.navigateTo({
  							  url: '/pages/myPage/address/address'//添加成功后自动跳地址管理
  							});
  					      } else {
  					        uni.showToast({
  					          title: "地址修改失败：" + response.data,
  					          icon: "none"
  					        });
  					      }
  					    },
  					    fail(err) {
  					      console.error("提交失败", err);
  					      uni.showToast({
  					        title: "提交失败，请检查网络",
  					        icon: "none"
  					      });
  					    }
  					  });
  		} else {
  			uni.showToast({
  				title: '无法获取经纬度，请检查地址是否正确',
  				icon: 'none'
  			});
  		}
  	},
  	fail: (err) => {
  		uni.showToast({
  			title: '请求失败，请检查网络',
  			icon: 'none'
  		});
  		console.error('请求失败:', err);
  	}
  });
};

// 获取当前位置
const getLocation = () => {
    uni.getLocation({
        type: 'wgs84', 
        success(res) {
            console.log("经度" + res.longitude + "纬度" + res.latitude);
			longitude.value=res.longitude;
			latitude.value=res.latitude;
            // 调用高德地图反向地理编码API
            uni.request({
                url: `https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=${res.longitude},${res.latitude}&key=fb7014bb45af62eac3d0a2e34eb63918&radius=1000&extensions=all`,
                success(regeoRes) {
                    console.log(regeoRes);
                    if (regeoRes.statusCode === 200 && regeoRes.data.status === "1") {
                        // 解析返回的地址信息
                        const addressComponent = regeoRes.data.regeocode.addressComponent;
                        const formattedAddress = regeoRes.data.regeocode.formatted_address;

                        console.log("详细地址信息：", addressComponent);
                        console.log("格式化地址：", formattedAddress);

                        // 提取国家、省、市、区、街道等信息
                        province.value = addressComponent.province;
                        city.value = addressComponent.city;
                        district.value = addressComponent.district;
                        street.value = addressComponent.township;
						postalcode.value=addressComponent.adcode;
                    } else {
                        uni.showToast({
                            title: "地址解析失败：" + regeoRes.data.info,
                            icon: "none"
                        });
                    }
                },
                fail(err) {
                    console.error("反向地理编码请求失败", err);
                    uni.showToast({
                        title: "反向地理编码请求失败",
                        icon: "none"
                    });
                }
            });
        },
        fail(err) {
            console.error("获取位置失败", err);
            uni.showToast({
                title: "授权失败，请开启位置权限",
                icon: "none"
            });
        }
    });
};
</script>

<style>
.container {
  padding: 20px;
}
.picker {
  padding: 10px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
}
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f5f5f5;
}

.form {
  width: 93%;
  max-width: 600px;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}

.label {
  font-size: 16px;
  color: #007aff;
  margin-bottom: 5px;
}

input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.picker {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  text-align: center;
}

.submit-button {
  width: 100%;
  max-width: 200px;
  background-color: #007aff;
  color: white;
  padding: 5px 20px;
  border-radius: 20px;
  margin-top: 20px;
}
</style>